const express = require('express');
//创建路由对象
const dairy = express.Router();
//引入数据库
const pool = require('../pool/pool');

// 1.首页查询 `最新三篇日记`接口
dairy.post('/selectThree', (req, res, next) => {
  let sql = `select * from pet_diary ORDER BY d_id DESC limit 0,3`;
  pool.query(sql, (err, result) => {
    if (err) {
      next(err);
      return;
    }
    console.log(result);
    if (result.length === 0) {
      res.send({ code: 201, msg: '查询失败' });
    } else {
      res.send({ code: 200, msg: '查询成功', data: result });
    }
  });
});
// 2.查询`全部日记`接口
dairy.post('/selectAll', (req, res, next) => {
  let obj = req.body;
  let pageNum = obj.pageNum;
  let pageSize = obj.pageSize;
  //4.2 执行SQL命令，从数据表pet_diary 分页 查询数据
  let sql = `select * from pet_diary ORDER BY d_id DESC limit ${pageNum},${pageSize}`;
  pool.query(sql, [pageNum, pageSize], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    console.log(result);
    if (result.length === 0) {
      res.send({ code: 201, msg: '查询失败', data: result });
    } else {
      res.send({ code: 200, msg: '查询成功', data: result });
    }
  });
});
// 3.通过日记`ID`查询日记
dairy.post('/selectByid', (req, res, next) => {
  let obj = req.body;
  let d_id = obj.d_id;
  let sql = `select * from pet_diary where d_id=?`;
  pool.query(sql, [d_id], (err, data) => {
    if (err) {
      next(err);
      return;
    }
    console.log(data);
    if (data.length === 0) {
      res.send({ code: 201, msg: '查询失败' });
    } else {
      res.send({ code: 200, msg: '查询日记成功', data: data });
    }
  });
});

//导出
module.exports = dairy;
